//
//  UIKTableViewCell.swift
//  UIKTableViewCell
//
//  Created by Fineland on 2021/3/11.
//

import UIKit

class UIKTableViewCell: UITableViewCell, UITextFieldDelegate {
    
    //标题
    private(set) var titleNameLabel: UILabel!
    //值
    private(set) var valueTextField: UITextField!
    private(set) var valueSwitch: UISwitch!
    private(set) var valueStepper: UIKStepper!
    //key值
    private(set) var key: String!
    
    //名称宽度
    private var widthName: CGFloat = 94.0
    //最大长度
    private var maxLength: Int = 0
    
    //闭包
    typealias ReturnClosure = (_ key: String, _ value: NSKCellValueModel) -> Void
    //回调
    var valueChanged: ReturnClosure?
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        //名称
        titleNameLabel = UILabel()
        titleNameLabel.font = UIFont.systemFont(ofSize: 16.0)
        titleNameLabel.numberOfLines = 0
        titleNameLabel.textColor = NSKVar.C3_COLOR
        //添加
        self.contentView.addSubview(titleNameLabel)
        //选中样式
        self.selectionStyle = .none
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let size = self.frame.size
        //调整rect值
        let rect1 = CGRect(x: NSKVar.kLR20, y: 0.0, width: widthName, height: size.height)
        //textField是否为空？
        if nil != valueTextField {
            //是否有指引？
            let offsetVal = NSKVar.kLR20 + (nil != self.accessoryView ? 18.0 : 0.0)
            let rect2 = CGRect(x: rect1.maxX, y: 0.0, width: size.width - rect1.maxX - offsetVal, height: size.height)
            valueTextField.frame = rect2
        }
        //switch是否为空？
        if nil != valueSwitch {
            var rect = valueSwitch.frame
            rect.origin = CGPoint(x: size.width - NSKVar.kLR20 - rect.size.width, y: 0.5 * (size.height - rect.size.height))
            valueSwitch.frame = rect
        }
        //stepper是否为空？
        if nil != valueStepper {
            var rect = valueStepper.frame
            rect.origin = CGPoint(x: size.width - NSKVar.kLR20 - rect.size.width, y: 0.5 * (size.height - rect.size.height))
            valueStepper.frame = rect
        }
        //RECT值
        titleNameLabel.frame = rect1
    }
    
    func attributes(_ attrObj: NSKCellModel) -> Void {
        
        //key值
        key = attrObj.valueKey
        //名称
        titleNameLabel.attributedText = attrName(attrObj.name, subTitle: attrObj.subTitle,
                                                 icon: attrObj.tagImage)
        //当前类型
        let typeVal = attrObj.cellType ?? "T"
        switch typeVal {
        case "T": textField(attrObj)
        case "S": swh()
        case "N": stepperNumber()
        case "Z": updateZ()
        default: break
        }
        //标题宽度
        if let wVal = attrObj.widthName {
            widthName = wVal
        }
        //是否需要indicator视图？
        self.accessoryView = nil
        if true == ((attrObj.showIndicator ?? 0) > 0) {
            //自定义indicator视图
            let tempView = UIImageView(image: UIImage(named: "system_indicator_black"))
            self.accessoryView = tempView
        }
    }
    
    func updateValue(_ value: NSKCellValueModel?) -> Void {
        
        //textField是否为空？
        if nil != valueTextField {
            valueTextField.attributedText = updateAttrValue(value)
            return
        }
        //switch是否为空？
        if nil != valueSwitch {
            var tempVal: Bool = false
            if let valueObj = value {
                tempVal = "0" != valueObj.value
            }
            valueSwitch.setOn(tempVal, animated: true)
        }
        //stepper是否为空？
        if nil != valueStepper {
            var tempVal = 0
            if let valueObj = value {
                tempVal = Int(valueObj.value ?? "0") ?? 0
            }
            valueStepper.value = tempVal
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
    private func textField(_ attrObj: NSKCellModel) -> Void {
        
        //是否为空？
        if nil == valueTextField {
            valueTextField = UITextField()
            valueTextField.font = titleNameLabel.font
            valueTextField.borderStyle = .none
            valueTextField.textAlignment = .right
            valueTextField.delegate = self
            valueTextField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
            //添加
            self.contentView.addSubview(valueTextField)
        }
        valueTextField.isHidden = false
        //switch是否为空？
        if nil != valueSwitch {
            valueSwitch.isHidden = true
        }
        //stepper是否为空？
        if nil != valueStepper {
            valueStepper.isHidden = true
        }
        //placeholder值
        valueTextField.placeholder = attrObj.placeholder
        //键盘类型
        if let keyboardTypeVal = attrObj.keyboard {
            switch keyboardTypeVal {
            case "D":
                datePicker()
            case "T":
                datePicker(.time)
            default:
                valueTextField.keyboardType(keyboardTypeVal)
            }
        }
        //颜色
        valueTextField.textColor = nil != attrObj.valueColor ? attrObj.valueColor!.color() : NSKVar.C3_COLOR
        //是否可编辑？
        valueTextField.isEnabled = attrObj.canEdit ?? 0 > 0
        //是否有后缀？
        rightView(attrObj.suffix, icon: attrObj.suffixIcon)
    }
    
    private func swh() -> Void {
        
        //是否为空？
        if nil == valueSwitch {
            valueSwitch = UISwitch()
            valueSwitch.onTintColor = NSKVar.MAIN_COLOR
            valueSwitch.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
            //添加
            self.contentView.addSubview(valueSwitch)
        }
        valueSwitch.isHidden = false
        //textField是否为空？
        if nil != valueTextField {
            valueTextField.isHidden = true
        }
        //stepper是否为空？
        if nil != valueStepper {
            valueStepper.isHidden = true
        }
    }
    
    private func stepperNumber() -> Void {
        
        //是否为空？
        if nil == valueStepper {
            valueStepper = UIKStepper()
            valueStepper.valueChanged = { [unowned self] (value: Int) -> Void in
                //回调是否为空？
                if let tempClosure = self.valueChanged {
                    let valueObj = NSKCellValueModel(value: "\(value)")
                    tempClosure(self.key, valueObj)
                }
            }
            //添加
            self.contentView.addSubview(valueStepper)
        }
        valueStepper.isHidden = false
        //textField是否为空？
        if nil != valueTextField {
            valueTextField.isHidden = true
        }
        //switch是否为空？
        if nil != valueSwitch {
            valueSwitch.isHidden = true
        }
    }
    
    private func updateZ() -> Void {
        
        //textField是否为空？
        if nil != valueTextField {
            valueTextField.isHidden = true
        }
        //switch是否为空？
        if nil != valueSwitch {
            valueSwitch.isHidden = true
        }
        //stepper是否为空？
        if nil != valueStepper {
            valueStepper.isHidden = true
        }
    }
    
    private func attrName(_ name: String, subTitle: String?, icon: String?) -> NSAttributedString {
        
        var tempVal: NSMutableAttributedString!
        //是否为空？
        if let subVal = subTitle {
            //行高
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 4.0
            let tempAttr1 = [NSAttributedString.Key.paragraphStyle: paragraphStyle]
            //属性
            let tempAttr2 = [
                NSAttributedString.Key.foregroundColor: NSKVar.C9_COLOR,
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13.0)
            ]
            //值
            tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: name, attributes: tempAttr1))
            tempVal.append(NSAttributedString(string: subVal, attributes: tempAttr2))
            //返回
            return tempVal
        }
        //是否有图标？
        if let iconVal = icon {
            //图片大小
            let szImg = CGSize(width: 20.0, height: 20.0)
            let attachment = NSTextAttachment()
            attachment.bounds = CGRect(origin: CGPoint(x: 0.0, y: -3.5), size: szImg)
            attachment.image = UIImage(named: iconVal)
            //值
            tempVal = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            tempVal.append(NSAttributedString(string: "  " + name))
        }
        else {
            tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: name))
        }
        //返回
        return tempVal
    }
    
    private func updateAttrValue(_ value: NSKCellValueModel?) -> NSAttributedString? {
        
        //是否为空？
        guard let valueObj = value  else {
            return nil
        }
        let tempVal = NSMutableAttributedString(attributedString: NSAttributedString(string: valueObj.value!))
        //是否存在原值？
        if let originVal = valueObj.originValue {
            let tempAttr = [
                NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12.0),
                NSAttributedString.Key.strikethroughStyle: NSNumber(1.5),
                NSAttributedString.Key.foregroundColor: NSKVar.C9_COLOR
            ]
            tempVal.append(NSAttributedString(string: "  "))
            tempVal.append(NSAttributedString(string: originVal, attributes: tempAttr))
        }
        //是否为自定义键盘？
        if let tempView = valueTextField.inputView {
            //是否为：“日期类型”？
            if let datePicker = tempView as? UIDatePicker {
                datePicker.date = valueObj.value!.toDate("yyyy-MMd-dd")
            }
        }
        //返回
        return tempVal
    }
    
    @objc private func endOnExit() -> Void {
        
        //关闭键盘
        valueTextField.resignFirstResponder()
    }
    
    @objc private func textChanged(_ textField: UITextField) -> Void {
        
        //回调是否为空？
        if let tempClosure = valueChanged {
            let valueObj = NSKCellValueModel(value: textField.text ?? "")
            tempClosure(key, valueObj)
        }
    }
    
    @objc private func switchChanged(_ sender: UISwitch) -> Void {
        
        //回调是否为空？
        if let tempClosure = valueChanged {
            let valueObj = NSKCellValueModel(value: true != sender.isOn ? "0" : "1")
            tempClosure(key, valueObj)
        }
    }
    
    private func datePicker(_ mode: UIDatePicker.Mode = .date) -> Void {
        
        //日期选择器
        let datePicker = UIDatePicker(frame: CGRect(x: 0.0, y: 0.0, width: NSKVar.kScreenWidth, height: 216.0))
        //区域设置为中文
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.datePickerMode = mode
        datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
        if #available(iOS 13.4, *) {
            datePicker.preferredDatePickerStyle = .wheels
        }
        valueTextField.inputView = datePicker
    }
    
    private func rightView(_ text: String?, icon: String?) -> Void {
        
        //是否有“文本”类型后缀？
        if let textVal = text {
            let tempLabel = UILabel()
            tempLabel.textColor = valueTextField.textColor
            tempLabel.font = valueTextField.font
            tempLabel.text = "  " + textVal
            tempLabel.sizeToFit()
            valueTextField.rightView = tempLabel
            valueTextField.rightViewMode = .always
            return
        }
        //是否有“图标”类型？
        if let iconVal = icon {
            let whImg: CGFloat = 20.0
            let imgView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: whImg, height: whImg))
            imgView.image = UIImage(named: iconVal)
            valueTextField.rightView = imgView
            valueTextField.rightViewMode = .always
            return
        }
        //置空
        valueTextField.rightView = nil
        valueTextField.rightViewMode = .never
    }
    
    @objc private func dateChanged(_ sender: UIDatePicker) {
        
        //格式化类型
        var fmtVal = ""
        switch sender.datePickerMode {
        case .time:
            fmtVal = "HH:mm"
        default:
            fmtVal = "yyyy-MM-dd"
        }
        //更新日期
        valueTextField.text = sender.date.toString(fmtVal)
        //回调是否为空？
        if let tempClosure = valueChanged {
            let valueObj = NSKCellValueModel(value: valueTextField.text!)
            tempClosure(key, valueObj)
        }
    }
    
    // MARK: - UITextField Delegate
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        //值是否为空？
        if "" != textField.text {
            return
        }
        //默认日期（包括时间）
        if let datePicker = textField.inputView as? UIDatePicker {
            return dateChanged(datePicker)
        }
    }
     
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        //当前长度
        let tempVal = (textField.text?.count ?? 0) - range.length + string.count
        //返回
        return maxLength < 1 || tempVal <= maxLength
    }
}

// MARK: -

extension UITextField {
    
    fileprivate func keyboardType(_ type: String) -> Void {
        
        //当前类型
        switch type {
        case "E": self.keyboardType = .emailAddress
        case "N": self.keyboardType = .numberPad
        case "P": self.keyboardType = .phonePad
        case "F": self.keyboardType = .decimalPad
        case "A": self.keyboardType = .asciiCapable
        case "A2":
            self.keyboardType = .asciiCapable
            self.autocapitalizationType = .allCharacters
        default:
            break
        }
    }
}
